import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/global/global_api.dart';
import 'package:flutter_app/main/main/model/account_title_entity.dart';
import 'package:flutter_app/main/main/official_accounts/account_child.dart';

class AccountWidget extends StatefulWidget {
  const AccountWidget({super.key});

  @override
  AccountPage createState() => AccountPage();
}

class AccountPage extends State<AccountWidget>
    with SingleTickerProviderStateMixin {
  List<AccountTitleData> titleList = [];
  int count = 0;
  late TabController tabController;
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

  Future<void> getTitleData() async {
    String url = GlobalApi.publicTitleUrl;
    Response response = await Dio().get(url);
    var data = response.data;
    AccountTitleEntity listEntity = AccountTitleEntity.fromJson(data);
    setState(() {
      titleList.addAll(listEntity.data);
      count = titleList.length;
      tabController = TabController(length: count, vsync: this);
    });
  }

  @override
  void initState() {
    getTitleData();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      appBar: PreferredSize(
          preferredSize: const Size.fromHeight(40),
          child: AppBar(
            elevation: 0,
            title: count > 0
                ? TabBar(
                    controller: tabController,
                    padding: const EdgeInsets.only(bottom: 8),
                    unselectedLabelColor: Colors.white54,
                    unselectedLabelStyle: const TextStyle(fontSize: 15),
                    labelStyle: const TextStyle(fontSize: 15),
                    physics: const BouncingScrollPhysics(),
                    indicatorWeight: 0.1,
                    isScrollable: true,
                    tabs: titleList.map((e) => Tab(text: e.name)).toList(),
                  )
                : null,
          )),
      body: count > 0
          ? TabBarView(
              //构建
              controller: tabController,
              children: titleList.map((e) {
                return AccountChildWidget(e.id);
              }).toList(),
            )
          : null,
    );
  }
}
